/**
 * @file workspace_parser.cpp
 * @brief Implementation of Code::Blocks workspace parser
 * @author AI Assistant
 * @date 2025-10-13
 * @version 1.0
 */

#include "workspace_parser.h"
#include <wx/filename.h>
#include <wx/datetime.h>
#include <wx/utils.h> // for wxExecute
#include <wx/tokenzr.h>

WorkspaceParser::WorkspaceParser() {
    m_stats.totalProjects = 0;
    m_stats.totalFiles = 0;
    m_stats.totalFunctions = 0;
    m_stats.processingTime = 0.0;
}

WorkspaceParser::~WorkspaceParser() {
    // 清理资源
}

bool WorkspaceParser::IsWorkspaceFile(const wxString& filename) {
    wxString ext = wxFileName(filename).GetExt().Lower();
    return ext == "workspace" || ext == "cbworkspace";
}

bool WorkspaceParser::ParseWorkspace(const wxString& workspaceFile) {
    if (!IsWorkspaceFile(workspaceFile)) {
        wxLogError("不是有效的workspace文件: %s", workspaceFile);
        return false;
    }

    m_workspaceFile = workspaceFile;
    m_workspacePath = wxFileName(workspaceFile).GetPath();
    
    if (!wxFileExists(workspaceFile)) {
        wxLogError("workspace文件不存在: %s", workspaceFile);
        return false;
    }

    return ParseWorkspaceXML();
}

bool WorkspaceParser::ParseWorkspaceXML() {
    if (!m_xmlDoc.Load(m_workspaceFile)) {
        wxLogError("无法加载workspace XML文件: %s", m_workspaceFile);
        return false;
    }

    wxXmlNode* root = m_xmlDoc.GetRoot();
    if (!root || root->GetName() != "CodeBlocks_workspace_file") {
        wxLogError("无效的workspace文件格式");
        return false;
    }

    // 查找Workspace节点
    wxXmlNode* workspaceNode = nullptr;
    for (wxXmlNode* child = root->GetChildren(); child; child = child->GetNext()) {
        if (child->GetName() == "Workspace") {
            workspaceNode = child;
            break;
        }
    }

    if (!workspaceNode) {
        wxLogError("未找到Workspace节点");
        return false;
    }

    // 获取workspace标题
    m_workspaceTitle = workspaceNode->GetAttribute("title", "UntitledWorkspace");

    // 解析项目
    m_projects.clear();
    for (wxXmlNode* projNode = workspaceNode->GetChildren(); projNode; projNode = projNode->GetNext()) {
        if (projNode->GetName() == "Project") {
            WorkspaceProject project;
            project.filename = projNode->GetAttribute("filename", "");
            project.active = projNode->GetAttribute("active", "1") == "1";
            
            if (!project.filename.IsEmpty()) {
                // 构建完整路径
                wxFileName fn(project.filename);
                if (!fn.IsAbsolute()) {
                    fn.MakeAbsolute(m_workspacePath);
                }
                project.path = fn.GetFullPath();
                project.title = ExtractProjectTitle(project.path);
                
                m_projects.push_back(project);
            }
        }
    }

    m_stats.totalProjects = m_projects.size();
    return true;
}

wxString WorkspaceParser::ExtractProjectTitle(const wxString& cbpFile) {
    if (!wxFileExists(cbpFile)) {
        return wxFileName(cbpFile).GetName();
    }

    wxXmlDocument doc;
    if (doc.Load(cbpFile)) {
        wxXmlNode* root = doc.GetRoot();
        if (root && root->GetName() == "CodeBlocks_project_file") {
            for (wxXmlNode* child = root->GetChildren(); child; child = child->GetNext()) {
                if (child->GetName() == "Project") {
                    wxString title = child->GetAttribute("title", "");
                    if (!title.IsEmpty()) return title;
                }
            }
        }
    }
    
    return wxFileName(cbpFile).GetName();
}

bool WorkspaceParser::ExecuteCBPProcessor(const wxString& cbpFile, bool silent) {
    if (!wxFileExists(cbpFile)) {
        if (!silent) wxPrintf("❌ 项目文件不存在: %s\n", cbpFile);
        return false;
    }

    // 调用现有的cbp2make_ai处理器
    wxString command = wxString::Format(
        "cbp2make_ai.exe --ai-mode cbp2make_aicoder \"%s\"", 
        cbpFile
    );

    long result = wxExecute(command, wxEXEC_SYNC | wxEXEC_NOHIDE);
    if (result != 0) {
        if (!silent) wxPrintf("❌ 处理项目失败: %s, 返回值: %ld\n", cbpFile, result);
        return false;
    }

    return true;
}

bool WorkspaceParser::ProcessAllProjects(bool silent) {
    wxDateTime startTime = wxDateTime::Now();
    int successCount = 0;
    
    if (!silent) {
        wxPrintf("🔄 开始处理workspace中的所有项目...\n");
    }
    
    for (size_t i = 0; i < m_projects.size(); i++) {
        const WorkspaceProject& project = m_projects[i];
        if (!silent) {
            wxPrintf("  处理项目 %d/%d: %s\n", (int)i + 1, (int)m_projects.size(), project.filename);
        }
        
        if (ExecuteCBPProcessor(project.path, silent)) {
            successCount++;
            if (!silent) {
                wxPrintf("  ✅ 成功处理: %s\n", project.filename);
            }
        } else {
            if (!silent) {
                wxPrintf("  ❌ 处理失败: %s\n", project.filename);
            }
        }
    }
    
    m_stats.processingTime = (wxDateTime::Now() - startTime).GetSeconds().ToDouble();
    if (!silent) {
        wxPrintf("📊 项目处理完成: %d/%d 成功, 耗时: %.2f 秒\n", 
                 successCount, m_projects.size(), m_stats.processingTime);
    }
    
    return successCount > 0;
}

wxString WorkspaceParser::GenerateWorkspaceHeader() const {
    wxString header;
    header << "/**\n";
    header << " * @workspace " << m_workspaceTitle << "\n";
    header << " * @brief Multi-project workspace configuration\n";
    header << " * @author AI Assistant\n";
    header << " * @date " << wxDateTime::Now().FormatISODate() << "\n";
    header << " * @version 1.0\n";
    header << " * @contains " << m_projects.size() << " projects\n";
    header << " */\n\n";
    return header;
}

bool WorkspaceParser::GenerateWorkspaceComments(bool silent) {
    if (!ProcessAllProjects(silent)) {
        if (!silent) wxPrintf("❌ 处理workspace项目失败\n");
        return false;
    }
    
    // 生成workspace报告
    wxString report = GenerateWorkspaceHeader();
    report << "// 📝 WORKSPACE COMMENT GENERATION REPORT\n";
    report << "// ==========================================\n\n";
    report << "// 🏢 Workspace: " << m_workspaceTitle << "\n";
    report << "// 📁 Location: " << m_workspaceFile << "\n";
    report << "// 📊 Total Projects: " << m_projects.size() << "\n";
    report << "// ⏱️ Processing Time: " << wxString::Format("%.2f", m_stats.processingTime) << " seconds\n\n";
    
    report << "// 📦 Projects Processed:\n";
    for (const auto& project : m_projects) {
        report << "//    ✅ " << project.title << " (" << project.filename << ")\n";
    }
    
    // 保存报告
    wxString reportFile = wxFileName(m_workspaceFile).GetName() + "_comment_report.txt";
    wxFile file(reportFile, wxFile::write);
    if (file.IsOpened()) {
        file.Write(report);
        file.Close();
        if (!silent) {
            wxPrintf("📄 Workspace报告已保存: %s\n", reportFile);
        }
    }
    
    return true;
}
